package com.itqf.demo02;

import com.itqf.utils.ConnectionUtils;
import com.itqf.utils.SysConstant;
import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * @Description:
 * @Company: 千锋互联
 * @Author: 李丽婷
 * @Date: 2021/3/12
 * @Time: 上午9:33
 */
public class Rec2 {
    public  static  void  main(String[]args) throws  Exception{

        Connection connection = ConnectionUtils.getConnection();
        //通道 Channel
        Channel channel = connection.createChannel();
        //队列
        //(String queue, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments
        channel.queueDeclare(SysConstant.WORK_QUEUE_NAME,false,false,false,null);

        //每次消费1条消息，
        channel.basicQos(1);
        //消费完毕才去消费另一个，能实现根据消费者能力消费消息
        //消费者
        DefaultConsumer defaultConsumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
               //接收到消息
                System.out.println("消费者2："+new String(body));
                //业务处理
                //持久化到db
               // int i = 10/0;

                try {
                    //模拟耗时操作
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println("处理业务");
                System.out.println("持久化到数据库");
                System.out.println("业务处理 end!~~");
                //long deliveryTag, boolean multiple
                //手动应答
                //参数一：tag
                //参数二:是否通知mq所有的消费者都接到消息
                channel.basicAck(envelope.getDeliveryTag(),false);

            }
        };
        //String queue, boolean autoAck, Consumer callback
        //true:自动应答  自动通知MQ接到消息，mq的就会把消息删除
        channel.basicConsume(SysConstant.WORK_QUEUE_NAME,false,defaultConsumer);

        System.in.read();

        channel.close();
        connection.close();



    }


}
